<template>
    <div class="cart">
        <!-- 购物车开头 -->
        <div class="cart-box" v-show=" goodsList.length > 0">
            <div class="cart-title">
                <span class="all">共<i>{{cartCount()||0}}</i>件商品</span>
                <span class="edit" @click="isEdit=!isEdit">
                    <van-icon name="edit" />
                    编辑
                </span>
            </div>
        </div>
        <div class="cart-container">
            <van-empty v-show=" goodsList.length === 0" description="购物车目前还没有商品" :image="cartEmptyImage">
                <router-link :to="{ name: 'category' }">
                    <van-button round type="danger" class="bottom-button">去购物</van-button>
                </router-link>
            </van-empty>
            <!-- 购物车列表 -->
            <div v-for="item in goodsList" :key="item.id" class="list">
                <van-swipe-cell>
                    <!-- 复选框 -->
                    <div class="checkbox">
                        <van-checkbox  v-show="!isEdit" :name="item" v-model="item.checked" @change="onCheck" checked-color="#f11a27"></van-checkbox>
                        <van-button class="delbtn" color="red" style="width: 20px; height: 50px;" v-show="isEdit" @click="onDelete(item)">删除</van-button>
                    </div>
                    
                    <!-- 商品图片 -->
                    <div class="image">
                        <router-link :to="{ name: 'goodsDetail', params: { id: item.id} }">
                            <van-image width="50" height="50" :src="item.picture" />
                        </router-link>
                    </div>
                    <!-- 商品信息 -->
                    <div class="goods-info">
                        <div>{{ item.goods_name }}</div>
                        <div class="bottom">
                            <div class="price"><span>￥</span>{{ (item.goods_price*item.num).toFixed(1) }}</div>
                            <van-stepper v-model="item.num" theme="round" button-size="22" disable-input/>
                        </div>
                    </div>
                </van-swipe-cell>
            </div>
        <van-submit-bar v-show="goodsList.length" :price="total * 100" button-text="去结算" button-type="primary" @submit="onSubmit" class="settlement">
            <van-checkbox v-model="allChecked" checked-color="#f11a27" @click="onCheckAll">全选</van-checkbox>
        </van-submit-bar>
    </div>  
</div>
</template>

<script setup>
import cartEmptyImage from '@/assets/images/cart_empty.png'
import { ref, onBeforeMount, computed, onUpdated } from 'vue'
import useCart from '../../stores/cart'
const { removeCart, cartCount, loadCartp, cartValue } = useCart()
import { useRoute } from 'vue-router';
const route = useRoute()
const goodsList = ref([])
const allChecked = ref(false)
onBeforeMount(async() => {
    await loadCart()
    onCheck()
})

onUpdated(()=>{
    goodsList.value = cartValue()
    // console.log(goodsList.value);   
    goodsList.value.forEach(good => {
        if (good.checked === undefined) {
            good.checked = true;  // 确保每个商品对象有 checked 属性
        }
    })
})


// 加载购物车数据
const loadCart = async () => {
    loadCartp()
    goodsList.value = cartValue()
    // console.log(cartValue());
    // console.log(goodsList.value);   
    goodsList.value.forEach(good => {
        if (good.checked === undefined) {
            good.checked = true;  // 确保每个商品对象有 checked 属性
        }
    })
    // console.log(goodsList.value);
    
}

const isEdit=ref(false);

import { removeFromCart } from '@/api'

const onDelete = item => {
    const id = item.id
    const goods_id=item.goods_id   
    goodsList.value = goodsList.value.filter(good => good.id !== id) // 重新赋值，确保响应式生效
    removeCart(id)
    // onCheck()
    removeFromCart({goods_id})
    isEdit.value=!isEdit.value
}


// 总金额
const total = computed(() => {
    let sum = 0
    goodsList.value.forEach(item => {
        if (item.checked) {
            sum += item.goods_price * item.num
        }
    })
    return sum
})

// 全选
const onCheckAll = () => {
    goodsList.value.forEach(el => {
        el.checked = allChecked.value
    })
}

// import { showToast } from 'vant'
// 去结算
const onSubmit = () => {
    // showToast('暂无后续逻辑~')
    router.push('/mypay')
}

const onCheck = () => {
    allChecked.value = goodsList.value.every(el => el.checked)
}

import { onBeforeUnmount } from 'vue'
import router from '@/router';
const { updateCart, delAll, addInfoToCart } =useCart()
//页面离开时保存购物车编辑内容
onBeforeUnmount(()=>{
    delAll()
    goodsList.value.forEach(good =>{
        addInfoToCart(good)
    })
    updateCart()
})
</script>

<style lang="less" scoped>
.cart {
    margin: 0.3rem;
    padding: .05rem 0 3rem 0;
    .cart-container {
        margin-top: 1rem;
        .list {
            position: relative;
            height: 5rem;
            border-radius: 10px;
            box-shadow: 0px 0px 5px #ccc;
            margin-bottom: 1rem;
            .checkbox {
                position: absolute;
                top: 1.7rem;
                left: .4rem;
                .delbtn{
                    top:-1rem;
                }
            }
            .image {
                position: absolute;
                top: .7rem;
                left: 3rem;
            }
            .goods-info {
                height: 5rem;
                display: flex;
                justify-content: space-around;
                flex-direction: column;
                padding: 0 1rem 0 7rem;
                .bottom {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .price {
                        color: #c82519;
                        font-size: .80rem;
                    }
                }
            }
            .delete-button {
                width: 2rem;
                height: 100%;
            }
        }
        .bottom-button {
            width: 7rem;
            height: 2rem;
        }
    }
    .settlement {
        margin-bottom: -0.1rem;
    }
}
:deep(.van-submit-bar) {
    bottom: 3.5rem;
}
:deep(.van-swipe-cell) {
    width: 100%;
}

.cart-title {
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    font-size: 14px;
    .all {
      i {
        font-style: normal;
        margin: 0 2px;
        color: #fa2209;
        font-size: 16px;
      }
    }
    .edit {
      .van-icon {
        font-size: 18px;
      }
    }
  }
</style>